package com.shizhanzhe.gxb.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shizhanzhe.gxb.R;
import com.shizhanzhe.gxb.WXLoginActivity;
import com.shizhanzhe.gxb.base.BaseFragment;
import com.shizhanzhe.gxb.base.UserBean;
import com.shizhanzhe.gxb.home.activity.PDDDetailActivity;
import com.shizhanzhe.gxb.home.adapter.PDDAdapter;
import com.shizhanzhe.gxb.home.bean.PDD;
import com.shizhanzhe.gxb.url.Path;
import com.shizhanzhe.gxb.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.gxb.widget.SortView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.Unbinder;

/**
 * Created by YJ on 2019/1/3.
 */
public class VPFragment extends BaseFragment implements SortView.notifyOutsideListener {
//    @BindView(R.id.lv_share)
    ListView lvShare;
//    @BindView(R.id.nodata)
    ImageView nodata;
    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;
    Unbinder unbinder;
    Drawable[] sortDrawable;
    List<String> sortType = Arrays.asList("综合", "价格", "佣金");
    @BindView(R.id.sortView)
    SortView sortView;
    private String id;
    private Context mContext;

    public static VPFragment newInstance(String id) {
        Bundle args = new Bundle();
        args.putString("id", id);
        VPFragment fragment = new VPFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getString("id");
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        lvShare = view.findViewById(R.id.lv_share);
        nodata = view.findViewById(R.id.nodata);
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_vp;
    }

    @Override
    protected void initView() {
        if ("120".equals(id)){
            sortView.setVisibility(View.GONE);
        } else {
            sortView.setVisibility(View.VISIBLE);
        }
        sortDrawable = new Drawable[]{ContextCompat.getDrawable(getContext(), R.mipmap.icon_sort_defalut), ContextCompat.getDrawable(getContext(), R.mipmap.icon_sort_true), ContextCompat.getDrawable(getContext(), R.mipmap.icon_sort_false)};
        sortView.setType(sortType, sortDrawable);
        sortView.setNotifyOutsideListener(this);
        refresh.setRefreshHeader(new ClassicsHeader(getActivity()));
        refresh.setRefreshFooter(new ClassicsFooter(getActivity()));
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                data.clear();
                getData();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                String url = "";
                if ("120".equals(id)) {
                    url = Path.pdd_recommend(page);
                } else {
                    url = Path.PDD(id, type, page);
                }
                OkHttpDownloadJsonUtil.downloadJson(getContext(), url, new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {
                        if (!"1".equals(json) && !"2".equals(json)) {
                            try {
                                Gson gson = new Gson();
                                List<PDD.DataBeanX.DataBean> list = gson.fromJson(json, PDD.class).getData().getData();
                                if (list.size() == 0) {
                                    Toast.makeText(getContext(), "已加载全部", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                data.addAll(list);
                                adapter.notifyDataSetChanged();
                            } catch (Exception e) {
                                Log.d("____",e.toString());
                                Toast.makeText(getContext(), "数据异常", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getContext(), "网络异常", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                refreshLayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
        getData();
    }

    private int type = 1;
    private int page = 1;
    private String itemid = "";
    private int itemposition = -1;
    private PDDAdapter adapter;
    private List<PDD.DataBeanX.DataBean> data = new ArrayList<>();

    private void getData() {
        String url = "";
        if ("120".equals(id)) {
            url = Path.pdd_recommend(page);
        } else {
            url = Path.PDD(id, type, page);
        }
        OkHttpDownloadJsonUtil.downloadJson(getContext(), url, new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        Gson gson = new Gson();
                        data = gson.fromJson(json, PDD.class).getData().getData();
                        if (data.size() == 0) {
//                            Toast.makeText(getContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                            lvShare.setVisibility(View.GONE);
                            nodata.setVisibility(View.VISIBLE);
                            return;
                        } else {
                            lvShare.setVisibility(View.VISIBLE);
                            nodata.setVisibility(View.GONE);
                        }
                        adapter = new PDDAdapter(data, getContext());
                        lvShare.setAdapter(adapter);
                        lvShare.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                if (UserBean.uid > 0) {
                                    itemposition = i;
                                    itemid = data.get(i).getGoods_id();
                                    startActivityForResult(new Intent(getContext(), PDDDetailActivity.class).putExtra("goods_id", Long.parseLong(data.get(i).getGoods_id())), 120);
                                } else {
                                    startActivity(new Intent(getContext(), WXLoginActivity.class));
                                }
                            }
                        });
                    } catch (Exception e) {
                        Toast.makeText(mContext, "数据异常", Toast.LENGTH_SHORT).show();
                        Log.i("__________", e.toString());
                    }
                } else {
                    Toast.makeText(mContext, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mContext = activity;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent d) {
        super.onActivityResult(requestCode, resultCode, d);
        if (resultCode == 120) {
            data.remove(itemposition);
            adapter.notifyDataSetChanged();
            OkHttpDownloadJsonUtil.downloadJson(getContext(), Path.PDDDELETE(itemid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                @Override
                public void onsendJson(String json) {
                }
            });
        }
    }

    @Override
    public void notifySort(String tag, int desOrasc) {
        page = 1;
        if (desOrasc == 0) {//由低到高
            if (tag.equals("价格")) {
                type = 2;
                getData();
            } else if (tag.equals("佣金")) {
                type = 4;
                getData();
            }
        } else {//由高到低
            if (tag.equals("综合")) {
                type = 1;
                getData();
            } else {
                if (tag.equals("价格")) {
                    type = 3;
                    getData();
                } else if (tag.equals("佣金")) {
                    type = 5;
                    getData();
                }
            }
        }
    }
}
